<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Random;
use think\Config;

use app\admin\model\Transactions as TransactionsModel;

class tenant extends api
{
    
      protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }
    
    public function info()
    {
           // 获取系统配置项
        $site = Config::get('site');
        return $this->success('返回成功', $site);
        
    }

    public function index()
    {
       $transactions = TransactionsModel::field('YEAR(transaction_time) as year, MONTH(transaction_time) as month, name,id, card_number, transaction_time, channel, counterpart_name, counterpart_account, counterpart_bank, amount, balance, remark,merchant,list_name')
            ->order('transaction_time', 'desc')
            ->select();
         $groupedTransactions = [];
        foreach ($transactions as $transaction) {
            $yearMonth = $transaction['year'] . '-' . str_pad($transaction['month'], 2, '0', STR_PAD_LEFT);
            if (!isset($groupedTransactions[$yearMonth])) {
                $groupedTransactions[$yearMonth] = [
                    'transactions' => [],
                    'income' => 0,
                    'expense' => 0
                ];
            }
            $transaction['transaction_time'] = date('Y-m-d g:i:s',strtotime($transaction['transaction_time']));
            $groupedTransactions[$yearMonth]['transactions'][] = $transaction;
            if ($transaction['amount'] > 0) {
                $groupedTransactions[$yearMonth]['income'] += $transaction['amount'];
            } else {
                $groupedTransactions[$yearMonth]['expense'] += abs($transaction['amount']);
            }
        }

        return $this->success('返回成功', $groupedTransactions);
        
    }
}